﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace joelblogs.co.uk.Locale.Stapler
{
    public class Utilities
    {
        /// <summary>
        /// Sets the locale for web.
        /// </summary>
        /// <param name="web">The web.</param>
        public static void SetLocaleForWeb(SPWeb web)
        {
            try
            {
                // find the Uri of the current web
                Uri currentWebUri = new Uri(web.Url);
                // work out the Uri for the root (e.g. 
                // http://webapp1/sites/site1/subsite1 becomes http://webapp1)
                UriBuilder rootWebUri = new UriBuilder(currentWebUri.Scheme, 
                    currentWebUri.Host, currentWebUri.Port);
                string rootSiteUrl = rootWebUri.ToString();
                // attempt to change the locale / regional settings by running as system...
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    // ...to access the root site/web of the web app
                    using (SPSite rootSite = new SPSite(rootSiteUrl))
                    {
                        using (SPWeb rootWeb = rootSite.RootWeb)
                        {
                            // ...and change the locale and regional settings of the current site
                            // to those of the root site collection root web's.
                            web.Locale = (System.Globalization.CultureInfo)rootWeb.Locale.Clone();
                            web.Update();
                            web.RegionalSettings = new SPRegionalSettings(rootWeb);
                            web.Update();
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                LogError(System.Reflection.MethodBase.GetCurrentMethod().Name, 
                    ex.Message, ex.StackTrace);
            }
        }

        /// <summary>
        /// Logs the error.
        /// </summary>
        /// <param name="CategoryName">Name of the category.</param>
        /// <param name="Message">The message.</param>
        /// <param name="StackTrace">The stack trace.</param>
        private static void LogError(string CategoryName, string Message, string StackTrace)
        {
            SPDiagnosticsService.Local.WriteTrace(0, 
                new SPDiagnosticsCategory(CategoryName, 
                    TraceSeverity.Unexpected, EventSeverity.Error), 
                TraceSeverity.Unexpected, Message, StackTrace);
        }
    }
}
